package com.galengao.springboot.validateAndResponse.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.galengao.springboot.validateAndResponse.eneity.ValidateEntity;
import com.galengao.springboot.validateAndResponse.resp.BaseResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 验证控制器校验
 *
 * @author GalenGao
 * @version Id: ValidateController.java, v 0.1 2022/5/30 13:49 GalenGao Exp $$
 */
@RestController
@RequestMapping("/validate")
public class ValidateController {

    /**
     * PathVariable校验，当请求不满足正则表达式则返回404
     * @param group
     * @param userId
     * @return
     */
    @GetMapping("/path/{group:[a-zA-Z-]+}/{userId}")
    public String path(@PathVariable("group") String group,@PathVariable("userId") Long userId) {
        return group+":"+userId;
    };


    @GetMapping("/hello/{hello}")
    public String path(@PathVariable("hello") String hello) {
        return hello;
    };

    @PostMapping("/add")
    public ResponseEntity<String> addEntity(@Valid @RequestBody ValidateEntity validateEntity, BindingResult bindingResult) {
        // 获取所有属性error信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        if(!CollectionUtils.isEmpty(fieldErrors)) {
            String defaultMessage = fieldErrors.get(0).getDefaultMessage();
            return ResponseEntity.ok(defaultMessage);
        }
        return ResponseEntity.ok("添加成功");
    }


    @PostMapping("/base/add")
    public BaseResponse<String> addBaseEntity(@Valid @RequestBody ValidateEntity validateEntity, BindingResult bindingResult) {
        // 获取所有属性error信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        if(!CollectionUtils.isEmpty(fieldErrors)) {
            String defaultMessage = fieldErrors.get(0).getDefaultMessage();
            return BaseResponse.fail(defaultMessage,500);
        }
        return BaseResponse.success();
    }

    public static void main(String[] args) throws Exception {
        ValidateEntity validateEntity = new ValidateEntity();
        validateEntity.setAddress("陕西西安");
        validateEntity.setName("张三");
        validateEntity.setAge(-3);
        String json = new ObjectMapper().writeValueAsString(validateEntity);
        System.out.println(json);
    }
}
